import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../api/DictApi.dart';
import '../../utils/Settings.dart';
import '../../utils/Utils.dart';
import '../../utils/dio/DioMethod.dart';
import '../../utils/dio/DioUtil.dart';
import '../queryform/LQueryFormLogic.dart';
import '../queryform/LQueryFormPage.dart';
import 'LCellListState.dart';

class LCellListLogic extends GetxController{

  final state = LCellListState();
  late String queryFormTag;

  void init({
    required String axiosUrl,
    required Function buildItemWidget,
    List? queryFormAttributes,
    String? dictCodes,
    List? dictCodeReplaceFields,
    List? initOrder,
    List? initQuery,
    bool? isAutoLoad = true,
    Map? queryFromData,
    int? pageSize = Settings.pageSize,
    String? tag

  }) async {

    state.axiosUrl = axiosUrl;
    state.buildItemWidget = buildItemWidget;
    state.queryFormAttributes = queryFormAttributes??[];
    state.dictCodes = dictCodes??"";
    state.dictCodeReplaceFields = dictCodeReplaceFields??[];
    state.initOrder = initOrder??[];
    state.initQuery = initQuery??[];
    state.isAutoLoad = isAutoLoad??true;
    state.queryFromData = queryFromData??{};
    state.pageSize = pageSize??Settings.pageSize;
    state.tag = tag??"";

    print("开始");
    if(!Utils.isEmpty(state.dictCodes)){
      await DictApi.initDict(state.dictCodes.toString(), "", state.dictCodeReplaceFields);
      print("下拉初始完成");
    }
    print("查询");
    if(state.isAutoLoad==true){
      onRefresh();
    }
    // 监听滚动事件
    state.scrollController.addListener((){
      // 获取滚动条下拉的距离
      // print(_scrollController.position.pixels);
      // 获取整个页面的高度
      // print(_scrollController.position.maxScrollExtent);
      if(state.scrollController.position.pixels>state.scrollController.position.maxScrollExtent-state.distance){
        searchQuery();
      }
    });

    //如果有查询，初始化查询
    if(state.queryFormAttributes.isNotEmpty){
      queryFormTag = '${state.tag}${Settings.queryFormEtSign}';
      LQueryFormLogic lQueryFormLogic = Get.put(LQueryFormLogic(),tag: queryFormTag);
      lQueryFormLogic.state.listTag = state.tag;
      lQueryFormLogic.init(queryFormAttributes: state.queryFormAttributes, queryFromData: state.queryFromData,tag: queryFormTag);
    }

  }


  ///初始化下拉数据
  initDict()async{
    if(!Utils.isEmpty(state.dictCodes)){
      await DictApi.initDict(state.dictCodes.toString(), "", state.dictCodeReplaceFields);
    }
  }

  ///下拉刷新
  void onRefresh()async{
    state.finished = false;
    state.dataCenter["pageNo"]=1;
    state.list.clear();
    state.list=[];
    await searchQuery();
  }

  void setInitQuery(List initQuery){
    state.initQuery = initQuery;
  }


  ///查询数据
  searchQuery()async{
    if(state.finished){
      return;
    }
    createDataCenter();
    dynamic res = await DioUtil.getInstance().request(state.axiosUrl,method: DioMethod.post,data: state.dataCenter);
    if(res["success"]==true){
      if(res["result"]!=null && res["result"].isNotEmpty){
        List records = [];
        if(res["result"].runtimeType.toString()=="List<dynamic>"){
          records = res["result"];
          state.finished=true;
        }else if(res["result"]["records"]!=null){
          records = res["result"]["records"];
          if(state.dataCenter["pageNo"]<res["result"]["pages"]){
            state.dataCenter["pageNo"] = state.dataCenter["pageNo"]+1;
            state.finished=false;
          }else{
            state.finished=true;
          }
        }
        ///如果是第一页，将原来数据清空
        // if(state.dataCenter["pageNo"]==1){
        //   state.list.clear();
        //   state.list=[];
        // }
        state.list.addAll(records);

      }else{
        state.finished = true;
      }
      update();
    }else{
      EasyLoading.showError(res["message"]);
      state.finished = true;
    }

  }

  ///构造查询和排序用到数据
  createDataCenter(){
    List orderColumns=[];
    List queryParamField=[];//临时存放QUERYFORM字段信息
    List queryFormVal = createQueryFormVal();
    if(queryFormVal.isNotEmpty){
      for(var item in queryFormVal){
        queryParamField.add(item['field']);
      }
    }
    //默认查询放到最后并过滤掉重复的查询条件
    if(state.initQuery.isNotEmpty){
      for (var v in state.initQuery) {
        if(queryParamField.isEmpty?true:!queryParamField.contains(v['field'])){
          queryFormVal.add(v);
        }
      }
    }


    //默认排序
    if(state.initOrder.isNotEmpty){
      for(var item in state.initOrder){
        if(item['val']!=null){
          orderColumns.add(item);
        }
      }
    }
    state.dataCenter["queryForm"] = queryFormVal;
    state.dataCenter["orderColumns"] = orderColumns;

  }

  ///构造查询信息
  createQueryFormVal(){
    List queryFormVal=[];
    if(state.queryFormAttributes.isEmpty){
      return queryFormVal;
    }

    for(var item in state.queryFormAttributes){
      if(item['condition']=='between'){
        if(!Utils.isEmpty(state.queryFromData!['${item["field"]}${Settings.stSign}'])){
          Map tempItem = {};
          tempItem['field'] = item['field'];
          tempItem['val'] = state.queryFromData!['${item["field"]}${Settings.stSign}'];
          tempItem['condition'] = "ge";
          queryFormVal.add(tempItem);
        }
        if(!Utils.isEmpty(state.queryFromData!['${item["field"]}${Settings.etSign}'])){
          Map tempItem = {};
          tempItem['field'] = item['field'];
          tempItem['val'] = state.queryFromData!['${item["field"]}${Settings.etSign}'];
          tempItem['condition'] = "le";
          queryFormVal.add(tempItem);
        }
      }else{
        if(!Utils.isEmpty(state.queryFromData!['${item["field"]}'])){
          Map tempItem = {};
          tempItem['field'] = item['field'];
          tempItem['condition'] = item['condition']??"eq";
          tempItem['val'] = state.queryFromData!['${item["field"]}'];
          queryFormVal.add(tempItem);
        }
      }

    }
    return queryFormVal;
  }

  /// 生成加载动画
  Widget createMoreWidget() {
    if(!state.finished){
      return Container(
        padding: const EdgeInsets.all(16.0),
        alignment: Alignment.center,
        child: const SizedBox(
          width: 24.0,
          height: 24.0,
          child: CircularProgressIndicator(strokeWidth: 2.0),
        ),
      );;
    }else{
      return Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(25.0),
        child: const Text("没有更多了",style: TextStyle(color: Colors.grey),),
      );
    }
  }


  Future<dynamic> showCustomModalBottomSheet(context) async {
    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            clipBehavior: Clip.antiAlias,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.0),
                topRight: Radius.circular(20.0),
              ),
            ),
            height: MediaQuery.of(context).size.height / 2.0,
            child: Column(
                children: [
                  SizedBox(
                    height: 50,
                    child: Stack(
                      textDirection: TextDirection.rtl,
                      children: [
                        const Center(
                          child: Text('筛选', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),),
                        ),
                        IconButton(
                            icon: const Icon(Icons.close),
                            onPressed: () {
                              Navigator.of(context).pop();
                            }),
                      ],
                    ),
                  ),
                  const Divider(height: 1.0),
                  Expanded(
                    child: LQueryFormPage(tag: queryFormTag),

                  ),
                ]
            ),
          ),
        );
      },
    );
  }


}